<?php


namespace App\Http\Controllers\Admin;


use App\Enums\CriticalEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IndependentPoolController extends BaseController
{
    private $pondTypeId;

    public function __construct(Request $request)
    {
        $this->pondTypeId = $request->pond_type;
        $pondType = app('model_independent_pool_type')->select('id')->where('id', $this->pondTypeId)->first();
        if (empty($pondType)) {
            throw new BasicException(10001);
        }
    }

    /**
     * @api {Get} /independentPool/pondGiftList 特殊独立奖池礼物列表
     * @apiGroup 补充接口-幸运树游戏
     *
     * @apiParam {Int} pond_type 奖池类型
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "list": [
    {
    "id": 1, 主键id
    "gift_id": 80, 礼物id
    "number": 11, 礼物数量
    "gift_name": "探索未来", 礼物名称
    "price": 99999, 礼物价格
    "picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/hbFcfzWaDr.png", 图片
    "special": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/bJFtdJP2bD.svga", 动效
    "quality": "紫色" 品质
    },
    {
    "id": 2,
    "gift_id": 81,
    "number": 20,
     "critical_times 暴击数量": 10,
    "gift_name": "梦之承载",
    "price": 52000,
    "picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/RPxEZsZpNy.png",
    "special": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/Ww2jKTQWDR.svga",
    "quality": "紫色"
    }
    ],
    "total": "2139989",
    "critical_gift_ids 可以暴击的礼物ids": [
    542,
    543
    ],
    "count": "31"
    }
    }
     */
    public function pondGiftList()
    {
        $list = app('model_independent_pool')->getIndependentPoolList($this->pondTypeId);
        $count = app('model_independent_pool')->getIndependentPoolCount($this->pondTypeId);
        $total = app('model_independent_pool')->getIndependentPoolTotal($this->pondTypeId);
        $criticalGifts = app('model_critical_prize')->getModuleGiftIds(CriticalEnum::MODULE_TREE);
        return Response::sendData([
            'list' => $list, 'total' => $total, 'count' => $count,
            'critical_gift_ids'  => $criticalGifts,
        ]);
    }

    /**
     * @api {Post} /independentPool/pondGiftAdd 新增盲盒奖池礼物
     * @apiGroup 补充接口-幸运树游戏
     *
     * @apiParam {Int} pond_type 奖池类型
     * @apiParam {Int} gift_id 礼物id
     * @apiParam {Int} num 礼物数量
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function pondGiftAdd(Request $request)
    {
        $giftId = $request->gift_id; //礼物id
        $num = $request->num; //礼物数量

        $this->paramVerify($giftId, $num);

        $data = [
            'type' => $this->pondTypeId,
            'gift_id' => $giftId,
            'number' => $num,
        ];
        $res = app('model_independent_pool')->insert($data);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '添加失败');
        }
    }

    /**
     * @api {Put} /independentPool/pondGiftEdit 奖池礼物编辑
     * @apiGroup 补充接口-幸运树游戏
     *
     * @apiParam {Int} pond_type 奖池类型
     * @apiParam {Int} gift_info 礼物修改信息，格式：id,礼物id,数量。多个用分号;连接，例如：1,78,10;2,79,20
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function pondGiftEdit(Request $request)
    {
        $giftInfo = $request->gift_info; //礼物修改信息，格式：id1,礼物id,数量1;id2,礼物id2,数量2 注意是英文逗号和分号

        //查询该奖池里所有礼物id
        $ids = app('model_independent_pool')->where('type', $this->pondTypeId)->pluck('id')->toArray();

        $giftInfo = explode(';', $giftInfo);

        //更新
        DB::beginTransaction();
        try {

            $selectedGiftIds = [];
            foreach ($giftInfo as $v) {
                if ($v) {
                    $poolGift = explode(',', $v);
                    //主键id
                    if (isset($poolGift[0])) {
                        $id = $poolGift[0];
                        if (!in_array($id, $ids)) throw new BasicException(10001);
                    } else throw new BasicException(10001);
                    //礼物id
                    if (isset($poolGift[1])) {
                        $giftId = $poolGift[1];
                        $selectedGiftIds[] = $giftId;
                    } else throw new BasicException(10001);
                    //数量
                    if (isset($poolGift[2])) {
                        $giftNum = $poolGift[2];
                    } else throw new BasicException(10001);

                    $this->paramVerify($giftId, $giftNum, $id);

                    app('model_independent_pool')
                        ->where('id', $id)
                        ->update(['gift_id' => $giftId, 'number' => $giftNum]);
                }
            }
            //判断是否选择了重复的礼物
            if (count($selectedGiftIds) != count(array_unique($selectedGiftIds))) throw new BasicException(0, '礼物重复');

            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    private function paramVerify($giftId, $num, $id = 0)
    {
        if (empty($giftId)) throw new BasicException(0, '请选择礼物');

        $gift = app('model_gift')
            ->where('id', $giftId)
            ->where('type', 2)
            ->where('sold', 1)
            ->value('id');
        if (empty($gift)) throw new BasicException(10001);

        $pollGift = app('model_independent_pool')->giftIsExist($this->pondTypeId, $giftId, $id);
        if ($pollGift) throw new BasicException(0, '礼物已经存在');

        if (!is_numeric($num) || $num < 0) throw new BasicException(0, '礼物数量有误');
    }

    /**
     * @api {Delete} /independentPool/pondGiftDel 删除奖池礼物
     *
     * @apiGroup 补充接口-幸运树游戏
     *
     * @apiParam {Int} pond_type 奖池类型
     * @apiParam {String} ids 盲盒礼物编号，多个用英文逗号连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function pondGiftDel(Request $request)
    {
        $ids = $request->ids; //盲盒礼物编号
        if (empty($ids)) {
            throw new BasicException(0, '参数缺失');
        }

        $ids = str_replace('"', '', $ids);
        $ids = str_replace('\'', '', $ids);
        $ids = str_replace(' ', '', $ids);
        $ids = explode(',', $ids);

        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                if ($id) {
                    $exist = app('model_independent_pool')->select('id')->where('id', $id)->first();
                    if ($exist) {
                        app('model_independent_pool')->where('id', $id)->delete();
                    } else {
                        throw new BasicException(10001);
                    }
                }
            }
            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, '删除失败');
        }
    }
}
